import uuid

import requests
from bs4 import BeautifulSoup
from pymysql import Connection


# 获取每个电影在指定区域可以放映的影院的页面源码
def get_movie_in_cinema(showId, area, headers):
    """
    获取每个电影在指定区域可以放映的影院的页面源码
    :param showId: 电影的标识
    :param area: 放映地区
    :return: 页面源码
    """
    url = 'https://dianying.taobao.com/showDetailSchedule.htm?'
    params = {
        'showId': showId,
        'regionName': area
    }
    response = requests.get(url=url, headers=headers, params=params)
    return response


# 获取每个电影在指定区域可以放映的影院
def parse_movie_in_cinema(showId_list, area, headers):
    """
    获取每个电影在指定区域可以放映的影院
    :param showId_list: 电影的id标识
    :param area: 可以放映地区
    :return: list((showId,list(area)))
    """
    # 循环遍历每个showId，解析每个电影在哪些影院放映的页面源码
    showId_areas_list = list()
    for showId in showId_list:
        response = get_movie_in_cinema(showId, area, headers)
        soup = BeautifulSoup(response.text, 'lxml')
        area_list_tag = soup.select('.filter-wrap > div > ul > li:nth-child(2) > div > a')
        # 存放影院名称
        area_list = list()
        # 将每个可以放映该电影的影院存入list中
        for area_tag in area_list_tag:
            area_list.append(area_tag.get_text())
        showId_areas_list.append((showId, area_list))
    return showId_areas_list


# 根据电影院名称，查询主键c_id
def query_id_by_name(c_name):
    """
    根据电影院名称，查询主键c_id
    :param c_name: 电影院名称
    :return: c_id
    """
    # 构建Mysql数据库的连接
    conn = Connection(
        host='localhost',  # 主机名
        port=3306,  # 端口号
        user="root",  # 用户名
        password="admin"  # 密码
    )
    # 获取游标对象
    cursor = conn.cursor()
    # 选择数据库
    conn.select_db("spider")
    # 执行查询性sql
    cursor.execute("select c_id from t_cinema where c_name=%s", (c_name))
    # 返回结果是一个嵌套元组
    results_tuple = cursor.fetchall()
    for r in results_tuple:
        return r[0]

# 将每个电影对应影院信息存入数据库
def save_movie_areas_in_mysql(showId_areas_list):
    """
    将每个电影对应影院信息存入数据库
    :param showId_areas_list: list((showId,list(area)))
    :return: None
    """
    # 构建Mysql数据库的连接
    conn = Connection(
        host='localhost',  # 主机名
        port=3306,  # 端口号
        user="root",  # 用户名
        password="admin"  # 密码
    )
    # 获取游标对象
    cursor = conn.cursor()
    # 选择数据库
    conn.select_db("spider")
    # 执行sql
    print(showId_areas_list)
    cimema_movie_list=list()
    for showId_areas in showId_areas_list:
        showId = showId_areas[0]
        areas = showId_areas[1]
        # 过滤该地区无法放映的电影
        if len(areas) > 0:
            # 遍历地区
            for area in areas:
                # 查询影院的id
                c_id = query_id_by_name(area)
                # 将能放映的电影和电影院存入数据库
                if c_id != None:
                    cimema_movie=CinemaMovie(uuid.uuid1().hex,showId,c_id)
                    cimema_movie_list.append(cimema_movie)
                    sql = "insert into t_cin_mov values(%s,%s,%s)"
                    vale = (cimema_movie.cm_id, cimema_movie.m_id, cimema_movie.c_id)
                    cursor.execute(sql, vale)
    # 通过commit提交
    conn.commit()
    # 关闭连接
    conn.close()


class CinemaMovie:

    def __init__(self, cm_id, m_id, c_id):
        """
        构造方法
        :param cm_id: 唯一标识符
        :param m_id: 电影标识符
        :param c_id: 影院标识符
        """
        self.cm_id = cm_id
        self.m_id = m_id
        self.c_id = c_id

    def __str__(self):
        return (self.cm_id + '-' + self.m_id + "-" + self.c_id)
